package com.mxy.myapplication.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mxy.myapplication.BuildConfig;
import com.mxy.myapplication.R;
import com.mxy.myapplication.asynctask.AsyncTaskForCompressPhoto;
import com.mxy.myapplication.asynctask.AsyncTaskForMakeRoundPhoto;
import com.mxy.myapplication.util.MyBottomSheetDialog;
import com.mxy.myapplication.util.Util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 拍照+裁剪+保存+显示
 */

public class ActivityForCutp extends BaseActivity implements View.OnClickListener {

    private ImageView iv;
    private ImageView iv2;
    private Button chosephoto, cutphoto;
    private TextView button;
    private MyBottomSheetDialog bottomSheetDialog;
    private BottomSheetBehavior bottomSheetBehavior;
    private ProgressDialog pd;
    private String photourl;//当前展示的图片地址
    private String[] permissions = new String[3];
    private Uri outputUri;//图片裁剪后输出路径
    private static MyHandler myHandler;

    /**
     * 不在UI线程中执行的handleMessage方法
     */
    private static class MyHandler extends Handler {

        private static WeakReference<ActivityForCutp> activityForCutpWeakReference;

        private MyHandler(ActivityForCutp activityForCutp) {
            activityForCutpWeakReference = new WeakReference<>(activityForCutp);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                ActivityForCutp activityForCutp = activityForCutpWeakReference.get();
                if (activityForCutp != null && !activityForCutp.isFinishing()) {
                    activityForCutp.handlerMessage(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void handlerMessage(Message msg) {
        if (pd != null) {
            pd.dismiss();
        }
        switch (msg.what) {
            case 0:
                if (msg.arg1 == 0) {//压缩图片完成，展示
                    Bitmap bitmap = (Bitmap) msg.obj;
                    iv.setImageBitmap(bitmap);
                } else {
                    Snackbar.make(iv, "压缩失败", Snackbar.LENGTH_SHORT).show();
                }
                break;
            case 1://裁剪完毕，展示
                iv.setImageBitmap((Bitmap) msg.obj);
                Snackbar.make(iv, "裁剪成功", Snackbar.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myHandler = new MyHandler(this);
        setContentView(R.layout.activity_cutphoto);

        permissions[0] = Manifest.permission.READ_EXTERNAL_STORAGE;
        permissions[1] = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        permissions[2] = Manifest.permission.CAMERA;


        iv = (ImageView) findViewById(R.id.iv);
        iv.setOnClickListener(this);

        chosephoto = (Button) findViewById(R.id.chosephoto);
        cutphoto = (Button) findViewById(R.id.cutphoto);

        chosephoto.setOnClickListener(this);
        cutphoto.setOnClickListener(this);

    }

    /**
     * 调起选择图片
     */
    private void chosePhoto() {
        Intent intent = new Intent();
        intent.setClass(this, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 6);
        // 选择模式  单张图片模式  imageselector还支持多张选择，需要将已经选择过的图片传过去
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, 0);
        //传入已选图片集合   注：要传uri  file://   不是绝对路径
//            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, photolist);
        //启动选择图像界面
        startActivityForResult(intent, 999);
    }

    @Override
    public void onClick(View v) {
        if (v == chosephoto) {//选择图片
            if (!checkPermissions(permissions)) {
                ActivityCompat.requestPermissions(ActivityForCutp.this, permissions, 0);
            } else {
                chosePhoto();
            }
        }
        if (v == cutphoto) {//裁剪图片
            if (photourl == null) {
                Snackbar.make(iv, "请先选择一张图片", Snackbar.LENGTH_SHORT).show();
            } else {
                try {
                    Intent intent = new Intent();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//安卓7.0及以上
                        // 将文件转换成content://Uri的形式     BuildConfig.APPLICATION_ID直接是应用的包名
                        Uri photoURI = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", new File(photourl));
                        // 申请临时访问权限
                        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                        intent.setDataAndType(photoURI, "image/*");// photouri是已经选择的图片Uri
                    } else {
                        Uri photoURI = Uri.parse("file://" + photourl);
                        intent.setDataAndType(photoURI, "image/*");// photouri是已经选择的图片Uri
                    }
                    intent.setAction("com.android.camera.action.CROP");
                    intent.putExtra("crop", "true");
                    intent.putExtra("scale", true);
                    intent.putExtra("aspectX", 1);// 裁剪框比例
                    intent.putExtra("aspectY", 1);
                    intent.putExtra("outputX", 500);// 输出图片大小
                    intent.putExtra("outputY", 500);
                    intent.putExtra("return-data", true);
                    //输出Uri不需要使用FileProvider
                    outputUri = Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/Camera/" + Util.getUUid() + ".jpg").getPath()));
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);

                    //调用安卓原生图片裁剪工具，进行图片裁剪
                    startActivityForResult(intent, 111);
                } catch (Exception e) {
                    e.printStackTrace();
                    Util.showToast(this, "您的手机不支持图片裁剪");
                }
            }
        }
        if (v == iv) {//BottomSheetDialog

            bottomSheetDialog = new MyBottomSheetDialog(ActivityForCutp.this);
            bottomSheetDialog.setCanceledOnTouchOutside(true);
            bottomSheetDialog.setCancelable(true);
            View view = getLayoutInflater().inflate(R.layout.bottomsheetdialog, null, false);
            RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.bottom_sheet_behavior);
            bottomSheetBehavior = BottomSheetBehavior.from(relativeLayout);
            bottomSheetBehavior.setPeekHeight(Util.dip2px(this, 240));
            button = (TextView) view.findViewById(R.id.button);
            button.setOnClickListener(this);
            iv2 = (ImageView) view.findViewById(R.id.iv2);
            bottomSheetDialog.setContentView(view);
            //这句话要在setContentView方法执行之后执行！！！
            bottomSheetDialog.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundResource(android.R.color.transparent);
            bottomSheetDialog.show();
        }
        if (v == button) {
            if (iv2.getVisibility() == View.VISIBLE) {
                iv2.setVisibility(View.GONE);
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            } else {
                iv2.setVisibility(View.VISIBLE);
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 999) {//选择图片
            if (resultCode == RESULT_OK) {
                pd = new ProgressDialog(this);
                pd.setMessage("压缩图片...");
                pd.setCancelable(false);
                pd.show();

                ArrayList<String> photoPaths = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                photourl = photoPaths.get(0);//单张图片选择模式，直接取就行了
                AsyncTaskForCompressPhoto as = new AsyncTaskForCompressPhoto(photourl, myHandler.obtainMessage(0));
                as.executeOnExecutor(Util.getExecutorService(), 1);
            }
        }

        if (requestCode == 111) {//裁剪图片
            if (resultCode == RESULT_OK) {
                pd = new ProgressDialog(this);
                pd.setMessage("裁剪图片...");
                pd.setCancelable(false);
                pd.show();

                try {
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(outputUri.getPath())));
                    Bitmap bitmap = BitmapFactory.decodeStream(bis);////由于裁剪的图片分辨率不高，我这里就直接读取并加载到内存了，但是如果不知道目标图片的分辨率是多少，一定不能这么干，分辨率过高会引起OOM，需要使用decodeStream另一个重载方法，先降低分辨率，再加载到内存
                    AsyncTaskForMakeRoundPhoto as = new AsyncTaskForMakeRoundPhoto(bitmap, myHandler.obtainMessage(1));
                    as.executeOnExecutor(Util.getExecutorService(), 1);
                } catch (Exception e) {
                    pd.dismiss();
                    e.printStackTrace();
                }
            }
        }
    }


    @Override  //只要开发者调用了requestPermissions方法,就算用户勾选了"不再提示"框，也会回调本方法
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (checkPermissions(permissions)) {
            chosePhoto();
        } else {
            showReasonAndRequestAgainIfCouldbe();
        }
    }

    /**
     * 检查所需权限是否都授予
     *
     * @param permissions 权限数组
     * @return 判断结果
     */
    private boolean checkPermissions(String[] permissions) {
        for (String perm : permissions) {
            if (ActivityCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 弹出对话框向用户解释为何需要该权限，并尝试再次请求权限
     * <p>
     * 注:shouldShowRequestPermissionRationale(Activity activity,String permission)方法
     * 如果用户已经授予该权限，此方法将返回false。
     * 如果应用之前请求过此权限但用户拒绝了请求，此方法将返回 true。
     * 如果用户在过去拒绝了权限请求，并在权限请求系统对话框中选择了 Don't ask again 选项，此方法将返回 false。
     */
    private void showReasonAndRequestAgainIfCouldbe() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            new AlertDialog.Builder(this)
                    .setTitle("需要权限")
                    .setMessage("该功能需要您授予拍照权限")
                    .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(ActivityForCutp.this, new String[]{Manifest.permission.CAMERA}, 0);
                        }
                    })
                    .setNegativeButton("拒绝", null)
                    .create().show();
        } else if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) && ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {//用户拒绝并勾选了“不再提示”框，跳转应用设置界面
            new AlertDialog.Builder(this)
                    .setTitle("需要权限")
                    .setMessage("该功能需要您授予拍照权限,请手动开启权限")
                    .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Uri packageURI = Uri.parse("package:" + getPackageName());
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton("拒绝", null)
                    .create().show();
        } else if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            new AlertDialog.Builder(this)
                    .setTitle("需要权限")
                    .setMessage("该功能需要读取您的内存卡上的图片")
                    .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(ActivityForCutp.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
                        }
                    })
                    .setNegativeButton("拒绝", null)
                    .create().show();
        } else if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE) && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {//用户拒绝并勾选了“不再提示”框，跳转应用设置界面
            new AlertDialog.Builder(this)
                    .setTitle("需要权限")
                    .setMessage("该功能需要读取您的内存卡上的图片,请手动开启权限")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Uri packageURI = Uri.parse("package:" + getPackageName());
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                            startActivity(intent);
                        }
                    })
                    .create().show();
        }
    }
}